using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Entity_DropManager : MonoBehaviour
{
    [SerializeField] private GameObject dropItemPrefab;
    [SerializeField] private ItemListDataSO dropItemList;
    [SerializeField] private float maxItemRarity = 1200f;
    [SerializeField] private int maxDropAmount = 3;


    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.V))
            DropItem();
    }
    public virtual void DropItem()
    {
        List<ItemDataSO> dropItemData = GetDropItemData();

        //返回最终能够掉落的物品的数量
        int finalDropAmount = Mathf.Min(dropItemData.Count, maxDropAmount);

        for (int i = 0; i < finalDropAmount; i++)
            CreateDropItem(dropItemData[i]);
    }

    protected void CreateDropItem(ItemDataSO itemData)
    {
        GameObject dropItem = PoolManager.Instance.Release(dropItemPrefab, (dropItem) =>
        {
            dropItem.transform.position = transform.position;
            dropItem.transform.rotation = Quaternion.identity;
        });
        dropItem.GetComponent<Object_ItemPuckup>().SetupItem(itemData);
    }
    /// <summary>
    /// 根据掉落物的稀有度和玩法属性得到最终能掉落的物品
    /// </summary>
    /// <returns></returns>
    private List<ItemDataSO> GetDropItemData()
    {
        List<ItemDataSO> possibleDropItem = new();
        List<ItemDataSO> finalDropItem = new();
        float maxItemRarity = this.maxItemRarity;
        //根据稀有度抽取物品存入列表
        foreach (var item in dropItemList.itemListData)
        {
            if (Random.Range(0, 100) < item.GetDropChance())
                possibleDropItem.Add(item);
        }

        //按照稀有度从高到低排序
        possibleDropItem.OrderByDescending(item => item.dropChance);

        //稀有度限制，得到的物品的稀有度之和要不超过规定的最大稀有度
        foreach (var item in possibleDropItem)
        {
            if (maxItemRarity >= item.itemRarity)
            {
                finalDropItem.Add(item);
                maxItemRarity -= item.itemRarity;
            }
            else break;
        }
        //返回掉落物的物品列表
        return finalDropItem;
    }
}
